package com.diyunapp.xilinapp.myindent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.OrderPayOuterAdapter;
import com.diyunapp.xilinapp.bean.OrderGoodsInBean;
import com.diyunapp.xilinapp.bean.OrderPayOutBean;
import com.diyunapp.xilinapp.details.PayCommitActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.MyOrdersClickInterface;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class WaitPayDetailActivity extends Activity implements View.OnClickListener{
    @Bind(R.id.order_waitpay_goback_ib)
    ImageButton orderWaitpayGobackIb;
    @Bind(R.id.state_detail)
    TextView stateDetail;
    @Bind(R.id.indent_money)
    TextView indentMoney;
    @Bind(R.id.indent_state)
    RelativeLayout indentState;
    @Bind(R.id.indent_user_name)
    TextView indentUserName;
    @Bind(R.id.indent_user_phone)
    TextView indentUserPhone;
    @Bind(R.id.indent_user_address)
    TextView indentUserAddress;
    @Bind(R.id.intent_address)
    RelativeLayout intentAddress;
    @Bind(R.id.order_waitpay_listview)
    ListView orderWaitpayListview;
    @Bind(R.id.order_delaypay_bn)
    TextView orderDelaypayBn;
    @Bind(R.id.order_paydo_bt)
    TextView orderPaydoBt;
    @Bind(R.id.orderpay_bottom_ll)
    LinearLayout orderpayBottomLl;

    //订单列表
    private List<OrderPayOutBean> myOrderList;
    private OrderPayOuterAdapter myOrderAdapter;

    private String order_id;
    private String pay_sn;
    private String orderid_listString = "";
    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_waitpay_layout);
        ButterKnife.bind(this);
        loginKey = MainActivity.myLogin.getLoginkey();
        pay_sn = getIntent().getStringExtra("PaySn");
        orderid_listString = getIntent().getStringExtra("orderIdString");
        initViews();
        getOrderList();
    }

    private void initViews() {
        myOrderList = new ArrayList<>();
        myOrderAdapter = new OrderPayOuterAdapter(myOrderList, this, new MyOrdersClickInterface() {
            @Override
            public void OnOrdersClick(View view, int operation, String info) {
                switch (view.getId()) {
                    case R.id.myorders_pay_bt:  //orderid 确认收货、立即评价等操作按钮
                        if (operation == 30)  //待收货 确认收货
                        {
                            sureToReceive(info);
                        }
                        else if (operation == 40)  //已收货 立即评价
                        {
                            Intent evaluationInt = new Intent(WaitPayDetailActivity.this, ReceiveListActivity.class);
                            evaluationInt.putExtra("OrderId", info);
                            startActivityForResult(evaluationInt, 2);
                        }
                        break;
                    case R.id.myorders_cancel_bt:  //orderid 取消订单、查看物流、删除订单
                        if (operation == 10) //待付款 取消订单
                        {
                            cancelOrder(info);
                        } else if (operation == 30) //待收货 查看物流
                        {
                            Intent wuliuInt = new Intent(WaitPayDetailActivity.this, CheckLogisticsActivity.class);
                            wuliuInt.putExtra("PaySn", info);
                            startActivityForResult(wuliuInt, 3);
                            break;
                        } else if (operation == 0 || operation == 40)  //订单已取消或已完成 删除订单
                        {
                            deleteOrder(info);
                        }
                        break;
                    case R.id.drawback_bt: //待发货、待收货、待评价时的退款退货按钮
                        if(operation == 40) //已收货的情况下，如果此按钮被设置，就是追加评论的功能
                        {
                            Intent addEvaluInt = new Intent(WaitPayDetailActivity.this, AddEvaluationActivity.class);
                            addEvaluInt.putExtra("OrderId", info);
                            Log.i("zhangxiaoxidebug","==="+info);
                            startActivity(addEvaluInt);
                        }
                        else if(operation==20)
                        {
                            Intent drawbackInt = new Intent(WaitPayDetailActivity.this, ApplyForRefundActivity.class);
                            drawbackInt.putExtra("order_id", info);
                            drawbackInt.putExtra("gd_id", "");
                            startActivityForResult(drawbackInt,4);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        orderWaitpayListview.setAdapter(myOrderAdapter);
        orderWaitpayGobackIb.setOnClickListener(this);
        orderDelaypayBn.setOnClickListener(this);
        orderPaydoBt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_waitpay_goback_ib:
                finish();
                break;
            case R.id.order_delaypay_bn:
                finish();
                break;
            case R.id.order_paydo_bt:
                Intent payInt = new Intent(this,PayCommitActivity.class);
                payInt.putExtra("PaySn",pay_sn);
                startActivityForResult(payInt,1);
                break;
        }
    }

    private void getOrderList() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_list";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("pay_sn", pay_sn);
        Log.i("xiaogaladebug","key+paysn"+loginKey+"===="+pay_sn);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "订单查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {
                        myOrderList.clear();
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "paysn_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");

                            JSONArray jsArrayGroup = jsObjectDatas.getJSONArray("order_group_list");
                            JSONObject jsObjectList = jsArrayGroup.getJSONObject(0);
                            JSONArray jsArrayOrder = jsObjectList.getJSONArray("order_list");

                            order_id = jsArrayOrder.getJSONObject(0).getString("order_id");
                            int orderState = 0;
                            getAddress();
                            for (int i = 0; i < jsArrayOrder.length(); i++) {
                                JSONObject jsObjectOrder = jsArrayOrder.getJSONObject(i);
                                String order_id = jsObjectOrder.getString("order_id");
                                if(!orderid_listString.isEmpty() && !orderid_listString.contains(order_id))
                                {
                                    continue;
                                }
                                String order_sn = jsObjectOrder.getString("order_sn");
                                String pay_sn = jsObjectOrder.getString("pay_sn");
                                String store_id = jsObjectOrder.getString("store_id");
                                String store_name = jsObjectOrder.getString("store_name");
                                String add_time = jsObjectOrder.getString("add_time");
                                String payment_code = jsObjectOrder.getString("payment_code");
                                String payment_time = jsObjectOrder.getString("payment_time");
                                String finnshed_time = jsObjectOrder.getString("finnshed_time");
                                String goods_amount = jsObjectOrder.getString("goods_amount");
                                String order_amount = jsObjectOrder.getString("order_amount");
                                String rcb_amount = jsObjectOrder.getString("rcb_amount");
                                String pd_amount = jsObjectOrder.getString("pd_amount");
                                String shipping_fee = jsObjectOrder.getString("shipping_fee");
                                String evaluation_state = jsObjectOrder.getString("evaluation_state");
                                String order_state = jsObjectOrder.getString("order_state");
                                orderState = Integer.parseInt(order_state);
                                String xlb_amount = jsObjectOrder.getString("xlb_amount");
                                String state_desc = jsObjectOrder.getString("state_desc");
                                String payment_name = jsObjectOrder.getString("payment_name");
                                String djj = jsObjectOrder.getString("djj");
                                String if_lock=jsObjectOrder.getString("if_lock");
                                String mansong = "";
                                if(jsObjectOrder.has("mansong"))
                                {
                                    mansong = jsObjectOrder.getString("mansong");
                                }
                                float goodsMoney_total = 0;
                                JSONArray jsArrayGoods = jsObjectOrder.getJSONArray("extend_order_goods");
                                List<OrderGoodsInBean> thegoodsList = new ArrayList<>();
                                for (int j = 0; j < jsArrayGoods.length(); j++) {
                                    JSONObject jsObjectGoods = jsArrayGoods.getJSONObject(j);
                                    String rec_id=jsObjectGoods.optString("rec_id");

                                    String goods_id = jsObjectGoods.getString("goods_id");
                                    String goods_name = jsObjectGoods.getString("goods_name");
                                    String goods_image_url = jsObjectGoods.getString("goods_image_url");
                                    String goods_price = jsObjectGoods.getString("goods_price");
                                    String goods_num = jsObjectGoods.getString("goods_num");
                                    goodsMoney_total += Float.parseFloat(goods_price)*Integer.parseInt(goods_num);
                                    thegoodsList.add(new OrderGoodsInBean(order_id,rec_id, goods_id, goods_name, goods_image_url, goods_price, goods_num, 0, 0));
                                }
                                goods_amount = String.valueOf(goodsMoney_total);
                                float orderMoney = FormatConfirm.stringToFloat(order_amount);
                                float xlbMoney = FormatConfirm.stringToFloat(xlb_amount);
                                String orderneedPay = String.valueOf(orderMoney-xlbMoney);
                                boolean ifDisplay = true;
                                myOrderList.add(new OrderPayOutBean(order_id,
                                        order_sn, pay_sn, store_id, store_name, add_time, payment_code, payment_time, finnshed_time,
                                        goods_amount, order_amount, rcb_amount, pd_amount, shipping_fee, evaluation_state, order_state,
                                        state_desc, xlb_amount, payment_name, thegoodsList, djj,if_lock, orderneedPay,ifDisplay,mansong));
                            }
                            myOrderAdapter.notifyDataSetChanged();

                            String pay_amount;
                            if(jsObjectList.has("pay_amount"))
                            {
                                pay_amount = jsObjectList.getString("pay_amount");
                                stateDetail.setText("等待买家付款");
                                indentMoney.setVisibility(View.VISIBLE);
                                indentMoney.setText("需在线支付金额：￥" + pay_amount);
                                orderpayBottomLl.setVisibility(View.VISIBLE);
                            }
                            else
                            {
                                switch (orderState)
                                {
                                    case 0:
                                        stateDetail.setText("订单已取消");
                                        break;
                                    case 20:
                                        stateDetail.setText("等待卖家发货");
                                        break;
                                    case 30:
                                        stateDetail.setText("卖家已发货");
                                        break;
                                    case 40:
                                        stateDetail.setText("订单已完成");
                                        break;
                                    default:
                                        stateDetail.setText("订单已完成");
                                        break;
                                }
                                indentMoney.setVisibility(View.GONE);
                                orderpayBottomLl.setVisibility(View.GONE);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "订单查询失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    public void getAddress() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=default_addresss&order_id=" + order_id;
        Log.i("zhangxiaoxidebug","getAddress url= "+url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                JSONObject jsObjectDatas = resultObject.getJSONObject("data");
                                String username = jsObjectDatas.getString("reciver_name");
                                JSONObject jsObjectInfo = jsObjectDatas.getJSONObject("reciver_info");
                                String phone =jsObjectInfo.getString("mob_phone");
                                if(phone.length()<=0)
                                {
                                    phone =jsObjectInfo.getString("tel_phone");
                                }

                                String address = jsObjectInfo.getString("address");

                                indentUserName.setText(username);
                                indentUserPhone.setText(phone);
                                indentUserAddress.setText(address);
                            }
                            else
                            {
                                Toast.makeText(getApplication(), "获取订单地址失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplication(), "获取订单地址失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplication(), "获取订单地址失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    public void sureToReceive(String orderid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_receive&key=" + loginKey
                + "&order_id=" + orderid;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {

                                String information = resultObject.getString("datas");
                                if (information.equals("1")) {
                                    Toast.makeText(getApplication(), "恭喜您，确认收货成功！", Toast.LENGTH_LONG).show();
                                    getOrderList();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getApplication(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplication(), "确认收货失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplication(), "确认收货失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    public void cancelOrder(String orderid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_order&op=order_cancel&key=" + loginKey
                + "&order_id=" + orderid;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String information = resultObject.getString("datas");
                                if (information.equals("1")) {
                                    Toast.makeText(getApplication(), "订单已取消！", Toast.LENGTH_LONG).show();
                                    getOrderList();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getApplication(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplication(), "订单取消失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplication(), "订单取消失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    public void deleteOrder(String orderid) {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods&op=del_order&member_id=" + MainActivity.myLogin.getMemberid()
                + "&order_id=" + orderid;
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String information = resultObject.getString("data");
                                if (information.equals("删除成功")) {
                                    Toast.makeText(getApplication(), information, Toast.LENGTH_LONG).show();
                                    finish();
                                } else {
                                    JSONObject errorObject = new JSONObject(information);
                                    String error = errorObject.getString("error");
                                    Toast.makeText(getApplication(), error, Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplication(), "订单删除失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplication(), "订单删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getOrderList();
        super.onActivityResult(requestCode, resultCode, data);
    }
}
